package com.ck.ips.controller;

import com.ck.common.model.File;
import com.ck.common.model.OperationResult;
import com.ck.common.model.Sysconfig;
import com.ck.core.annotation.LoginRequired;
import com.ck.core.constant.SysConfigNameEnum;
import com.ck.core.context.UserContextHolder;
import com.ck.core.exception.ServiceException;
import com.ck.core.util.SpiderUtils;
import com.ck.ips.service.file.FileGroupService;
import com.ck.ips.service.file.FileService;
import com.ck.ips.service.sys.SysConfigService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @description: 素材controller
 * @author: zhanglei
 * @date: 2019/4/30 9:36
 */
@LoginRequired
@Controller
@RequestMapping(value = "/file")
public class FileController {
    private static Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private FileService fileService;

    @Autowired
    private FileGroupService fileGroupService;

    @Autowired
    private SysConfigService sysConfigService;
    private String fileIdNotNullMsg = "文件id不能为空";

    /**
     * 上传图片文件接口
     * @param files 上传的文件
     * @return
     * @throws ServiceException
     * @throws IOException
     */
    @ResponseBody
    @PostMapping(value = "/uploadPicture")
    public Object uploadPicture(@Param("files") MultipartFile files)throws ServiceException, IOException{
        //云存储目录
        String cloudFileDir = "ckips/file/picture/";
        //文档文件全名（包含扩展名）
        String originalFilename = files.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            return OperationResult.newValidateFailOperationResult("文件不能为空");
        }
        originalFilename = originalFilename.replace(" ","");
        float unitSize = 1024 * 1024;
        //检测文件大小是否超标(获取图片限制大小),单位：M
        Sysconfig sysConfigVO = sysConfigService.getByType(SysConfigNameEnum.UPLOAD_MAX_PICTURE_SIZE);
        Float maxPictureSize = Float.parseFloat(sysConfigVO.getValue());
        if (files.getSize() > maxPictureSize * unitSize) {
            return OperationResult.newValidateFailOperationResult("只能上传图片文件，且不超过"
                    + maxPictureSize + "M");
        }
        //是否需要压缩
        boolean compress = false;
        Sysconfig sysConfigVO1 = sysConfigService.getByType(SysConfigNameEnum.PICTURE_COMPRESS_SIZE);
        Float pictureCompressSize = Float.parseFloat(sysConfigVO1.getValue());
        if(files.getSize() > pictureCompressSize * unitSize){
            compress = true;
        }

        //文档文件后缀
        String extension = FilenameUtils.getExtension(originalFilename);
        //文档文件名称
        String fileName = originalFilename.replaceAll("." + extension, "");
        if (StringUtils.isBlank(fileName.trim())) {
            return OperationResult.newValidateFailOperationResult("文件名称不能为空");
        }

        //获取允许上传的图片格式
        Sysconfig sysConfigVO2 = sysConfigService.getByType(SysConfigNameEnum.PASS_PICTURE_SUFFIX);
        String passPictureSuffix = sysConfigVO2.getValue();
        List<String> passPictureSuffixList = Arrays.asList(passPictureSuffix.split(","));
        if (!passPictureSuffixList.contains(extension)) {
            return OperationResult.newValidateFailOperationResult("文件格式不正确，请上传"+passPictureSuffix+"格式文件");
        }
        //上传至华为云
        File resultFile = fileService.uploadImage(files, cloudFileDir, fileName, extension,compress);
        //返回的参数
        List<File> fileList= new ArrayList<>();
        fileList.add(resultFile);
        return fileList;
    }

//    /**
//     * 上传图片文件接口（批量）
//     * @param files 上传的文件
//     * @return
//     * @throws ServiceException
//     * @throws IOException
//     */
//    @ResponseBody
//    @PostMapping(value = "/batchUploadPicture")
//    public OperationResult batchUploadPicture(@Param("files") List<MultipartFile> files){
//        //上传至华为云
//        try {
//            return fileService.batchUploadImage(files);
//        } catch (IOException | ServiceException e) {
//            logger.error("批量上传图片失败：{}", e.getMessage(), e);
//            return OperationResult.newValidateFailOperationResult("批量上传图片失败");
//        }
//    }

    /**
     * 上传视频文件接口
     * @param files 上传的文件
     * @return
     * @throws ServiceException
     * @throws IOException
     */
    @ResponseBody
    @PostMapping(value = "/uploadVideo")
    public Object uploadVideo(@Param("files") MultipartFile files){
        List<File> fileList= new ArrayList<File>();
        try  {
            //云存储目录
            String cloudFileDir = "ckips/file/video/";
            //文档文件全名（包含扩展名）
            String originalFilename = files.getOriginalFilename();
            if (StringUtils.isBlank(originalFilename)) {
                return OperationResult.newValidateFailOperationResult("文件不能为空");
            }
            originalFilename = originalFilename.replace(" ","");
            //文档文件后缀
            String extension = FilenameUtils.getExtension(originalFilename);
            //文档文件名称
            String fileName = originalFilename.replaceAll("." + extension, "");
            if (StringUtils.isBlank(fileName.trim())) {
                return OperationResult.newValidateFailOperationResult("文件名称不能为空");
            }
            //获取允许上传的视频格式
            Sysconfig sysConfigVO = sysConfigService.getByType(SysConfigNameEnum.PASS_VIDEO_SUFFIX);
            String passVideoSuffix = sysConfigVO.getValue();
            List<String> passVideoSuffixList = Arrays.asList(passVideoSuffix.split(","));
            if (!passVideoSuffixList.contains(extension)) {
                return OperationResult.newValidateFailOperationResult("文件格式不正确，请上传"+passVideoSuffix+"格式文件");
            }
            //视频限制上传大小
            Sysconfig sysConfigVideoMaxSize = sysConfigService.getByType(SysConfigNameEnum.UPLOAD_MAX_VIDEO_SIZE);
            Float maxVideoSize = Float.parseFloat(sysConfigVideoMaxSize.getValue());
            if (files.getSize() > maxVideoSize*1024*1024) {
                return OperationResult.newValidateFailOperationResult("只能上传视频文件不超过"+ maxVideoSize + "M");
            }
            //上传至华为云
            OperationResult<Object> resultFile = fileService.uploadVideo(files, cloudFileDir, fileName, extension);
            if(!resultFile.isSucess()){
                return resultFile;
            }
            fileList.add((File) resultFile.getData());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return OperationResult.newSystemErrorOperationResult();
        }
        return fileList;

    }

//    /**
//     * 确定上传文件接口（保存数据库信息）
//     * @param fileName 文件名称
//     * @param groupId 分组id
//     * @param fileStyle 文件类型
//     * @param fileUrl 文件地址
//     * @param fileImageUrl 文件缩略图
//     * @param md5 文件MD5值
//     * @param extension 文件后缀
//     * @param duration 文件时长
//     * @param size 文件大小
//     * @return
//     * @throws ServiceException
//     * @throws IOException
//     */
//    @ResponseBody
//    @PostMapping(value = "/uploadSure")
//    public Object uploadSure(String fileName,Long groupId,String fileStyle,String fileUrl,String fileImageUrl,String md5,String extension,Long duration,Long size) throws ServiceException, IOException {
//        //用户id
//        Long loginUserId = UserContextHolder.currentUser().getUserId();
//        //用户类型(1-商家 2-客户)
//        Integer loginUserType = 1;
//        //当前时间
//        Long date = System.currentTimeMillis();
//        //上传分组
//        if(groupId == null){
//            //获取默认分组id并默认分配到默认分组
//            groupId = fileGroupService.getDefaultGroupId();
//        }
//        //上传文件选择的类型
//        if(StringUtils.isBlank(fileStyle)){
//            return OperationResult.newValidateFailOperationResult("上传文件类型不能为空");
//        }
//        //自定义的文件名
//        if(fileName == null){
//            return OperationResult.newValidateFailOperationResult("文件名不能为空");
//        }
//        //判断文件名称不能包含特定字符串
//        String pattern = ".*"+ ElasticsearchConstant.SEPARATOR +".*";
//        boolean r = Pattern.matches(pattern,fileName);
//        if(r){
//            return OperationResult.newValidateFailOperationResult("文件名不能包含"+ElasticsearchConstant.SEPARATOR+"符号");
//        }
//        //文件地址
//        if(StringUtils.isBlank(fileUrl)){
//            return OperationResult.newValidateFailOperationResult("文件地址不能为空");
//        }
//        //如果文件类型不是web
//        if(!FileTypeEnum.WEB.getValue().equals(fileStyle)){
//            if(StringUtils.isBlank(md5)){
//                return OperationResult.newValidateFailOperationResult("文件MD5不能为空");
//            }
//            if(size ==  null){
//                return OperationResult.newValidateFailOperationResult("文件大小不能为空");
//            }
//            if(StringUtils.isBlank(extension)){
//                return OperationResult.newValidateFailOperationResult("文件后缀不能为空");
//            }
//            //文件缩略图
//            if(StringUtils.isBlank(fileImageUrl)){
//                return OperationResult.newValidateFailOperationResult("文件缩略图不能为空");
//            }
//            //如果文件类型不是image
//            if(!FileTypeEnum.IMAGE.getValue().equals(fileStyle)){
//                if(duration == null){
//                    return OperationResult.newValidateFailOperationResult("文件时长不能为空");
//                }
//                if(!FileTypeEnum.VIDEO.getValue().equals(fileStyle)){
//                    return OperationResult.newValidateFailOperationResult("文件类型错误");
//                }
//            }
//        }else{
//            extension=null;
//            size=1L;
//            md5=null;
//            duration=null;
//            Sysconfig sysConfigVO = sysConfigService.getByType(SysConfigNameEnum.DEFAULT_WEB_IMAGE);
//            String webDefaultImage = sysConfigVO.getValue();
//            fileImageUrl = webDefaultImage;
//        }
//        //保存信息至数据库
//        File returnFile = fileService.uploadSure(loginUserId,loginUserType,date,groupId,fileStyle,fileName,extension,md5,size,fileUrl,fileImageUrl,duration);
//        //记录日志
//        if(returnFile==null){
//            return OperationResult.newValidateFailOperationResult("该文件后缀类型已存在相同的文件名");
//        }
//        String msg = "添加文件fileName:"+returnFile.getFileName();
//        return OperationResult.newSuccessOperationResult(msg,returnFile);
//    }

    /**
     * 确定上传文件接口（保存数据库信息）
     * @param files 文件
     * @return
     * @throws ServiceException
     * @throws IOException
     */
    @ResponseBody
    @PostMapping(value = "/uploadSure")
    public Object uploadSure(@RequestParam String files) throws ServiceException, IOException {
        return fileService.batchUploadSure(files);
    }

    /**
     * 根据条件获取素材列表
     * @param fileName 搜索文件名
     * @param fileType 文件类型 type-en
     * @param fileGroupId 文件分组id
     * @param pageNum 当前页
     * @param pageSize 每页条数
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/getFileByPage")
    public Object getFileByPage(String fileName,String fileType,Long fileGroupId,Integer pageNum,Integer pageSize){
        if(StringUtils.isBlank(fileType)){
            return OperationResult.newValidateFailOperationResult("文件类型不能为空");
        }
        Page<File> files = fileService.getFileByPage(fileName,fileType,fileGroupId,pageNum,pageSize);
        PageInfo<File> pageInfo = new PageInfo<>(files);
        return pageInfo;
    }

    /**
     * 根据文件id删除文件
     * @param fileId 文件id
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/deleteFileById")
    public Object deleteFileById(Long fileId){
        //登陆用户id
        Long loginUserId = UserContextHolder.currentUser().getUserId();
        if(fileId==null){
            return OperationResult.newValidateFailOperationResult(fileIdNotNullMsg);
        }
        //删除文件
        return fileService.deleteFileById(fileId,loginUserId);
    }

    /**
     * 修改文件名称
     * @param fileName 新的文件名称
     * @param fileId 原文件id
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/updateFileNameById")
    public Object updateFileNameById(String fileName,Long fileId){
        //登陆用户id
        Long loginUserId = UserContextHolder.currentUser().getUserId();
        if(fileId==null){
            return OperationResult.newValidateFailOperationResult(fileIdNotNullMsg);
        }
        if(StringUtils.isBlank(fileName)){
            return OperationResult.newValidateFailOperationResult("文件名不能为空");
        }
        //检测上传的名字是否与该类型的已存在名字重复(其内需排除自己)
        boolean isExist = fileService.checkFileNameExist(fileName,fileId);
        if(isExist){
            return OperationResult.newValidateFailOperationResult("该类型的文件已存在相同的文件名，请重新命名");
        }
        //修改文件名
        return fileService.updateFileNameById(fileName,loginUserId,fileId);
    }

    /**
     * 修改文件分组
     * @param fileIds 文件id
     * @param fileGroupId 修改后的文件分组
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/updateFileGroupById")
    public Object updateFileGroupById(String fileIds,Long fileGroupId){
        //获取登陆人id
        Long loginUserId = UserContextHolder.currentUser().getUserId();
        if(StringUtils.isBlank(fileIds)){
            return OperationResult.newValidateFailOperationResult(fileIdNotNullMsg);
        }
        if(fileGroupId == null){
            return OperationResult.newValidateFailOperationResult("文件分组不能为空");
        }
        //修改文件分组
        return fileService.updateFileGroupById(fileIds,fileGroupId,loginUserId);
    }

    /**
     * 根据url获取网页title
     * @param url 网页地址
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/getTitleByUrl")
    public Object getTitleByUrl(String url){
        if(StringUtils.isBlank(url)){
            return OperationResult.newValidateFailOperationResult("地址不能为空");
        }
        String title = SpiderUtils.getTitleByUrl(url);
        if(StringUtils.isBlank(title)){
            return OperationResult.newValidateFailOperationResult("该网页无标题");
        }
        return title;
    }


}
